import { AjaxService, Req, Res } from "./ajax.service"
import { Injectable } from '@angular/core'

import { Project } from "./project"

@Injectable()
export class ProjectService {
  private bh = AjaxService.APIROOT + '/projects';

  update(project: Project): Promise<Res> {
    var argv = { project: project, token: localStorage.getItem("token") }
    if (project.id)
      return AjaxService.request(new Req(`${this.bh}/${project.id}.json`, "PUT", argv))
    else
      return AjaxService.request(new Req(`${this.bh}.json`, "POST", argv))
  }

  get(id: string): Promise<Project> {
    var project: Project
    return new Promise<Project>(resolve => {
      AjaxService.request(new Req(`${this.bh}/${id}.json`, "GET"))
          .then(res => {
            if (!res.error)
              project = res.data
            resolve()
          }).catch((err: any) => { console.log("get project error", err) })
    }).then(() => project)
  }
}
